package com.sftz.framework.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.uxuexi.core.common.util.Util;

/**
 * 小程序html工具
 * 
 */
public class WeappHtmlUtil {

	/**
	 * html标签
	 * <p>
	 * 以'<'开头后跟任意不是'>'的字符,最后以'>'结尾
	 */
	public final static String HTML_REGEX = "<([^>]*)>";

	/**前缀 + labelName + 后缀 -- 匹配标签labelName*/
	//html标签前缀
	public final static String HTML_PREFIX = "</?\\s*";
	//html标签后缀
	public final static String HTML_SUFFIX = "([^>]*)>";

	/**
	 * 替换指定的html标签
	 */
	public static String htmlReplace(String content, String labelName, String replacement) {
		if (!Util.isEmpty(content)) {
			String regex = HTML_PREFIX + labelName + HTML_SUFFIX;
			Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
			Matcher m = pattern.matcher(content);
			StringBuffer sb = new StringBuffer("");
			while (m.find()) {
				m.appendReplacement(sb, replacement);
			}
			m.appendTail(sb);
			return sb.toString();
		}
		return content;
	}

	/**
	 * 清空指定的html标签
	 */
	public static String clearHtml(String content, String labelName) {
		if (!Util.isEmpty(content)) {
			String regex = HTML_PREFIX + labelName + HTML_SUFFIX;
			Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
			Matcher m = pattern.matcher(content);
			StringBuffer sb = new StringBuffer("");
			while (m.find()) {
				m.appendReplacement(sb, "");
			}
			m.appendTail(sb);
			return sb.toString();
		}
		return content;
	}

}
